BINDING_HEADER_ACTIONPAD2   = "Action Pad2";

BINDING_NAME_ACTIONBUTTON13       = "Action Button 13";
BINDING_NAME_ACTIONBUTTON14       = "Action Button 14";
BINDING_NAME_ACTIONBUTTON15       = "Action Button 15";
BINDING_NAME_ACTIONBUTTON16       = "Action Button 16";
BINDING_NAME_ACTPADCONFIG         = "Configure Toggle";
BINDING_NAME_ACTPADTOGGLEMAINBAR  = "Show/Hide MainBar"
BINDING_NAME_ACTPADTOGGLEEXTRABAR = "Toggle AP ExtraBar";

local PRE_DBG = "";

function AP2_Noop()
end

local function debug(msg)
	if (DEFAULT_CHAT_FRAME ~= nil) then
		if (PRE_DBG ~= "") then
			DEFAULT_CHAT_FRAME:AddMessage(PRE_DBG);
		end
		DEFAULT_CHAT_FRAME:AddMessage(msg);
	else
		PRE_DBG = PRE_DBG .. msg .. "\n";
	end
end

ACTPAD2_SavedVars = {};

local function GetSavedVar(name,def)
	local key = GetRealmName() .. "_" .. UnitName("player") .. "_" .. name;
	
	if (ACTPAD2_SavedVars[key] ~= nil) then
		return ACTPAD2_SavedVars[key];
	end
	return def;
end

local function SetSavedVar(name,val)
	local key = GetRealmName() .. "_" .. UnitName("player") .. "_" .. name;
	ACTPAD2_SavedVars[key] = val;
end


-------------------------------------------------------------------------------------------
-- Global overrides


------------------------------------------------------------------------------------------------
-- Child Button Setup
local NUM_PAGES   = 6;
local NUM_BUTTONS = 16;

local RANGE_CHECK_UPDATE = .150;
local TOOL_TIP_UPDATE    = .150;
local REPEAT_UPDATE      = .150;
local COOLDOWN_UPDATE    = .150;

local MAIN_BAR_VIS = "main_bar_vis";
local EXTRA_BAR_VIS = "extra_bar_vis";

local ABUTTON_SIZE = 36

local LOADED = 0

AP2_Header_Frame = nil
AP2_Extra_Frame  = nil

local function SaveStealthPage()
	SetSavedVar("StealthPage",AP2_Header_Frame.StealthPage or -1)
end

local function SaveStancePages()
	for i = 1,GetNumShapeshiftForms() do
		SetSavedVar("StancePage" .. i,-1)
	end
	
	if AP2_Header_Frame.StancePages ~= nil then
		for i,v in pairs(AP2_Header_Frame.StancePages) do
			SetSavedVar("StancePage" .. i,v)
		end
	end
end

local function SaveModPages()
	if AP2_Header_Frame.ModPages ~= nil then
		for i,v in pairs(AP2_Header_Frame.ModPages) do
			SetSavedVar("ModPage"..i,v)
		end
	end
end

local function LoadStatePages()
	AP2_Header_Frame.StealthPage = GetSavedVar("StealthPage",-1)
	AP2_Header_Frame:Execute("StealthPage = " .. AP2_Header_Frame.StealthPage)
	
	AP2_Header_Frame.StancePages = {}
	AP2_Header_Frame:Execute("StancePages = newtable()")
	for i = 1,GetNumShapeshiftForms() do
		AP2_Header_Frame.StancePages[i] = GetSavedVar("StancePage" .. i,-1)
		AP2_Header_Frame:Execute("StancePages[" .. i .. "] = " .. AP2_Header_Frame.StancePages[i])
	end

	AP2_Header_Frame.ModPages = {}
	AP2_Header_Frame.ModPages["ctrl"] = GetSavedVar("ModPagectrl",-1)
	AP2_Header_Frame.ModPages["shift"] = GetSavedVar("ModPageshift",-1)
	AP2_Header_Frame.ModPages["alt"] = GetSavedVar("ModPagealt",-1)
	AP2_Header_Frame:Execute("ModPages = newtable()")
	AP2_Header_Frame:Execute("ModPages[\"ctrl\"]  = " .. GetSavedVar("ModPagectrl",-1))
	AP2_Header_Frame:Execute("ModPages[\"shift\"] = " .. GetSavedVar("ModPageshift",-1))
	AP2_Header_Frame:Execute("ModPages[\"alt\"]   = " .. GetSavedVar("ModPagealt",-1))
	
end

local UpdateCurrentPageItemCounts = nil

local function UpdateOverrideBindings(bindingPfx)
	ClearOverrideBindings(AP2_Header_Frame)
	
	if UnitHasVehicleUI('player') then
		return
	end
	
	local Children = {AP2_Header_Frame.CurrentPage:GetChildren()}
	
	for i = 1, NUM_BUTTONS do
		local key = GetBindingKey("ACTIONBUTTON"..i)
		if bindingPfx ~= nil then
			key = bindingPfx .. "-" .. key
		end
		SetOverrideBindingClick(AP2_Header_Frame,true,key,Children[i]:GetName())
	end
end

local Config_UpdatePage = nil

local function SetCurPageInfo(idxShow)
	for i,page in pairs(AP2_Header_Frame.Pages) do
		if i == idxShow then
			AP2_Header_Frame.CurrentPage = page
			AP2_Header_Frame.CurrentPageIdx = i
		end
	end
end

local function CreateExtraFrame()
	AP2_Extra_Frame = CreateFrame("Frame","AP2ExtraFrame",UIParent)
	AP2_Extra_Frame:SetMovable(1)
	AP2_Extra_Frame:ClearAllPoints()
	AP2_Extra_Frame:SetWidth(ABUTTON_SIZE*5)
	AP2_Extra_Frame:SetHeight(ABUTTON_SIZE*6)
	AP2_Extra_Frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
	AP2_Extra_Frame:EnableMouse(1)
	AP2_Extra_Frame:SetToplevel(1)
	AP2_Extra_Frame:SetFrameStrata("LOW")
	AP2_Extra_Frame:RegisterForDrag("LeftButton")
	AP2_Extra_Frame:SetBackdropColor(1,1,1,1)
	local t = AP2_Extra_Frame:CreateTexture(nil,"BACKGROUND")
	t:SetTexture(.5,.5,.5,.3)
	t:SetAllPoints(AP2_Extra_Frame)
	
	AP2_Extra_Frame:SetScript("OnDragStart", function(self,button)
										self:StartMoving()
									end)

	AP2_Extra_Frame:SetScript("OnDragStop", function(self)
										self:StopMovingOrSizing()
									end)
end

local function dumpstate(self, name, value)
	print(tostring(self) .. "  = (self) ")
	print(tostring(name) .. "  = (name) ")
	
	if (self == AP2_Header_Frame) then
		print("its the AP2 Hframe")
	else
		print("not ap2 frame " .. tostring(AP2_Header_Frame))
	end
	-- print(tostring(value) .. " (value)\n ")
end

local function CreateHeaderFrame()
	AP2_Header_Frame = CreateFrame("Frame","AP2Header",UIParent,"SecureHandlerStateTemplate")
	AP2_Header_Frame:SetMovable(1)
	AP2_Header_Frame:ClearAllPoints()
	AP2_Header_Frame:SetWidth(ABUTTON_SIZE*5)
	AP2_Header_Frame:SetHeight(ABUTTON_SIZE*4)
	AP2_Header_Frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
	AP2_Header_Frame:EnableMouse(1)
	AP2_Header_Frame:SetToplevel(1)
	AP2_Header_Frame:SetFrameStrata("LOW")
	AP2_Header_Frame:RegisterForDrag("LeftButton")
	AP2_Header_Frame:SetBackdropColor(1,1,1,1)
	local t = AP2_Header_Frame:CreateTexture(nil,"BACKGROUND")
	t:SetTexture(.5,.5,.5,.4)
	t:SetAllPoints(AP2_Header_Frame)
	
	-- hooksecurefunc("SecureHandler_StateOnAttributeChanged",dumpstate)
	
	t = AP2_Header_Frame:CreateTexture(nil,"ARTWORK")
	t:SetTexture("Interface\\Addons\\ActionPad2\\UP")
	t:SetWidth(36)
	t:SetHeight(28)
	t:SetPoint("TOPLEFT",AP2_Header_Frame,"TOPLEFT",72,-36)
	local UA = t
	
	t = AP2_Header_Frame:CreateTexture(nil,"ARTWORK")
	t:SetTexture("Interface\\Addons\\ActionPad2\\UP")
	t:SetWidth(36)
	t:SetHeight(28)
	t:SetPoint("TOPLEFT",UA ,"TOPLEFT",0,-45)
	t:SetTexCoord(0,1,1,0)
	local DA = t
	
	t = AP2_Header_Frame:CreateTexture(nil,"ARTWORK")
	t:SetTexture("Interface\\Addons\\ActionPad2\\LT")
	t:SetWidth(36)
	t:SetHeight(36)
	t:SetPoint("TOPLEFT",DA,"TOPLEFT",36,8)
	t:SetTexCoord(1,0,0,1)
	
	t = AP2_Header_Frame:CreateTexture(nil,"ARTWORK")
	t:SetTexture("Interface\\Addons\\ActionPad2\\LT")
	t:SetWidth(36)
	t:SetHeight(36)
	t:SetPoint("TOPLEFT",DA,"TOPLEFT",-36,8)
	
	t = AP2_Header_Frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
	t:SetAllPoints(AP2_Header_Frame)
	t:SetWidth(30)
	t:SetHeight(20)
	t:SetPoint("TOP",UT,"BOTTOM",0,0)
	t:SetText("(1/6)")
	AP2_Header_Frame.bank = t
	
	AP2_Header_Frame:SetScript("OnDragStart", function(self,button)
										self:StartMoving()
									end)

	AP2_Header_Frame:SetScript("OnDragStop", function(self)
										self:StopMovingOrSizing()
									end)
	AP2_Header_Frame.UpdateCurrentPageItemCounts = function(self)
		UpdateCurrentPageItemCounts()
	end
	AP2_Header_Frame.UpdateBank = function(self,index)
		self.bank:SetText(string.format("(%d/%d)",index,NUM_PAGES))
	end
	AP2_Header_Frame.Config_UpdatePage = function(self,index)
		if Config_UpdatePage ~= nil then
			Config_UpdatePage(index)
		end
	end
	AP2_Header_Frame.SetCurPageInfo = function (self,index)
		SetCurPageInfo(index)
	end
	
	AP2_Header_Frame:Execute("MAX_PAGE_COUNT = " .. NUM_PAGES)
	AP2_Header_Frame:Execute("MAX_BUTTON_COUNT = " .. NUM_BUTTONS)
	
	AP2_Header_Frame:SetAttribute("PetUpdate",[[
		if UnitHasVehicleUI('player') then
			self:ClearBindings()
		else
			control:RunAttribute("UpdateOverrideBindings",nil)
		end
	]])
	
	AP2_Header_Frame:SetAttribute("StanceUpdate",[[
		local newstate = 0
		local num = select("#",...)
		if num ~= nil and num > 0 then
			newstate = tonumber(select(1,...))
			if newstate == nil then
				newstate = 0
			end
		else
			newstate = 0
		end
		-- print("Stance to state: " .. newstate)
		if StancePages[newstate] ~= nil or newstate == 0 then
			if newstate == 0 then
				if StanceReturn ~= nil then
					control:RunAttribute("ShowPage",StanceReturn)
				end
				StanceReturn = nil
				if StealthReturn ~= nil then
					StealthReturn = CurrentPageIdx
				end
			else
				if StancePages[newstate] > -1 then
					TempReturn = nil
					if StealthReturn ~= nil then
						StanceReturn = StealthReturn
					else
						StanceReturn = CurrentPageIdx
					end
					StealthReturn = nil
					control:RunAttribute("ShowPage",StancePages[newstate])
				end
			end
		end
	]])
	
	AP2_Header_Frame:SetAttribute("PageUpdate",[[
		local newpage = tonumber(select(1,...))
		TempReturn    = nil
		StealthReturn = nil
		control:RunAttribute("ShowPage",newpage)
	]])
	
	AP2_Header_Frame:SetAttribute("UpdateOverrideBindings",[[
		local pfx = select(1,...)
		
		self:ClearBindings()
		
		if UnitHasVehicleUI('player') then
			return
		end
		
		for i = 1, MAX_BUTTON_COUNT do
			local key = GetBindingKey("ACTIONBUTTON"..i)
			if pfx ~= nil then
				key = pfx .. "-" .. key
			end
			-- print("Setting binding click on Button " .. self:GetFrameRef("Page"..CurrentPageIdx.."Button"..i):GetName() .. " with key " ..key)
			self:SetBindingClick(true,key,self:GetFrameRef("Page"..CurrentPageIdx.."Button"..i):GetName())
		end
	]])
	
	AP2_Header_Frame:SetAttribute("ShowPage",[[
		-- print("ShowPage")
		local p1 = select(1,...)
		local p2 = select(2,...)
		
		CurrentPageIdx = p1
		local BindingPrefix = p2
		
		for i = 1,MAX_PAGE_COUNT do
			if i == tonumber(CurrentPageIdx) then
				self:GetFrameRef("Page"..CurrentPageIdx):Show()
			else
				self:GetFrameRef("Page"..i):Hide()
			end
		end
		
		control:CallMethod("SetCurPageInfo",CurrentPageIdx)
		control:CallMethod("UpdateCurrentPageItemCounts")
		control:CallMethod("UpdateBank",CurrentPageIdx)
		control:CallMethod("Config_UpdatePage",CurrentPageIdx)
		control:RunAttribute("UpdateOverrideBindings",BindingPrefix)
	]])
	
	AP2_Header_Frame:SetAttribute("ModifierUpdate",[[
		-- print("ModifierUpdate")
		local newstate = select(1,...)
		if newstate == "off" or ModPages[newstate] ~= nil then
			if newstate == "off" then
				if TempReturn ~= nil then
					control:RunAttribute("ShowPage",TempReturn)
				end
				TempReturn = nil
			elseif ModPages[newstate]  > -1 then
				if TempReturn == nil then
					TempReturn = CurrentPageIdx
				end
				control:RunAttribute("ShowPage",ModPages[newstate],string.upper(newstate))
			end
		end
	]])
	
	AP2_Header_Frame:SetAttribute("StealthUpdate", [[
		-- print("StealthUpdate")
		local newstate = select(1,...)
		-- print("Stealth to state: " .. newstate)
		if StealthPage ~= nil then
			if newstate == "1" and StealthPage > -1 then
				if TempReturn ~= nil then
					StealthReturn = self.TempReturn
				else
					if StealthReturn == nil then
						StealthReturn = CurrentPageIdx
					end
				end
				TempReturn = nil
				control:RunAttribute("ShowPage",StealthPage)
			else
				if StealthReturn ~= nil then
					control:RunAttribute("ShowPage",StealthReturn)
				end
				StealthReturn = nil
				TempReturn    = nil
			end
		end
	]])
	
	AP2_Header_Frame.Pages = {}
	AP2_Header_Frame.CurrentPage = nil
end

local function button_CheckHotKey(self)
    local type = SecureButton_GetModifiedAttribute(self, "type", self, "");
	
    if (type == "action") then
		local action = SecureButton_GetModifiedAttribute(self, "action", self, nil);
		action = tonumber(action);
		if (action) then
			-- print("real action id " .. action)
			if action < NUM_BUTTONS * NUM_PAGES then
				action = mod(action,NUM_BUTTONS)
				if action == 0 then
					action = 16
				end
				local key1,key2 = GetBindingKey("ACTIONBUTTON" .. action)
				-- print("Got key1: " .. tostring(key1) .. " for action id " .. action)
				if (key1 ~= nil) then
					self.hotkey:SetText(GetBindingText(key1,"KEY_"));
				else
					self.hotkey:SetText("");
				end
			else
				self.hotkey:SetText("");
			end
		end
	end
end

local function InitializeActionButton(self)
	if self.tex == nil then
		self.tex = self:CreateTexture(nil,"BACKGROUND")
		self.tex:SetAllPoints(self)
	end
	local actionSlot = SecureButton_GetModifiedAttribute(self, "action")
	if not HasAction(actionSlot) then
		self.tex:SetTexture(.5,0,0,.3)
		self.tex:SetAlpha(1)
	else 
		self.tex:SetTexture(GetActionTexture(actionSlot))
	end
	
	button_CheckHotKey(self)
end

local function UpdateAllHotKeyText()
	for i,page in pairs(AP2_Header_Frame.Pages) do
		local children = {page:GetChildren()}
		for q,btn in ipairs(children) do
			button_CheckHotKey(btn)
		end
	end
end


local function button_CheckGrid(self)
	if (self.showgrid == 1) then
		if (not self.grid:IsVisible()) then
			self.grid:Show();
		end
	elseif (self.showgrid == 0) then
		if (self.grid:IsVisible()) then
			self.grid:Hide();
		end
	end
end

local function button_CheckRange(btn)
	local actionID = SecureButton_GetModifiedAttribute(btn, "action", button, nil);
	
	btn.hotkey:SetTextColor(.6,.6,.6);
	if (HasAction(actionID)) then
		if (ActionHasRange(actionID)) then
			local rangeFlag = IsActionInRange(actionID);
			
			if (rangeFlag == 1) then
				btn.hotkey:SetTextColor(0,1,0);
			elseif (rangeFlag == 0) then
				btn.hotkey:SetTextColor(1,0,0);
			end
		end
	end
end

local function button_CheckToolTip(btn)
	if (btn.toolTipTimeout ~= nil) then
		if (GameTooltip:IsOwned(btn:GetParent()) and btn:GetParent().toolTipOwner == btn) then
			if ( btn.toolTipTimeout > 0) then
				btn.toolTipTimeout = btn.toolTipTimeout - 1;
			else
				GameTooltip:Hide();
				btn.toolTipTimeout = nil;
				btn:GetParent().toolTipOwner = nil;
			end
		else
			btn.toolTipTimeout = 0;
		end
	end
	local frameID = GetMouseFocus();
	
	if (frameID ~= nil) then
		local mouseFrameName = frameID:GetName();
		if (mouseFrameName == btn:GetName()) then
			btn.toolTipTimeout = 1;
			GameTooltip:SetOwner(btn:GetParent(), "ANCHOR_BOTTOMRIGHT");
			btn:GetParent().toolTipOwner = btn;
			GameTooltip:SetAction(SecureButton_GetModifiedAttribute(btn, "action", button, nil));
		end
	end
end

local function button_RepeatUpdate(btn)
	local actionID = SecureButton_GetModifiedAttribute(btn, "action")
	
	if (IsCurrentAction(actionID) or IsAutoRepeatAction(actionID)) then
		if (IsAttackAction(actionID)) then
			if (btn.reptex:IsVisible()) then
				btn.reptex:Hide();
			else
				btn.reptex:Show();
			end
		else
			btn.grid:Show();
		end
	else
		if (btn.reptex:IsVisible()) then
			btn.reptex:Hide();
		end
		if (btn.grid:IsVisible() and (btn.showgrid or 0) == 0) then
			btn.grid:Hide();
		end
	end
end

local function button_CooldownUpdate(btn)
	local actionID = SecureButton_GetModifiedAttribute(btn, "action");
	local start, duration, enable = GetActionCooldown(actionID);
	if (start > 0) then
		if (btn.tex:GetAlpha() < 1) then
			btn.tex:SetAlpha(1);
		end
		
		local now = GetTime();
		local left = now - start;
		left = duration - left;
		if (left > 0) then
			local i,r = math.modf(left/60)
			r = r * 60;
			btn.cooldown:Show();
			btn.cooldownbk:Show();
			if (i > 0) then
				btn.cooldown:SetTextHeight(10);
				btn.cooldown:SetText(string.format("%d:%02d",i,r));
			else
				btn.cooldown:SetTextHeight(20);
				if (r < 1) then
					if (left < COOLDOWN_UPDATE) then
						btn.COOLDOWN_UPDATE = COOLDOWN_UPDATE - left; -- make the end of the cooldown exact.
					end
					btn.cooldown:SetText("*");
				else
					btn.cooldown:SetText(string.format("%d",r));
				end
			end
		else
			btn.cooldown:Hide();
			btn.cooldownbk:Hide();
		end
	else
		if (btn.cooldown:IsVisible()) then
			btn.cooldown:Hide();
			btn.cooldownbk:Hide();
		end
		if (HasAction(actionID)) then
			isUsable, notEnoughMana = IsUsableAction(actionID)
			if (isUsable) then
				if (btn.tex:GetAlpha() < 1) then
					btn.tex:SetAlpha(1);
				end
			else
				if (btn.tex:GetAlpha() > .2) then
					btn.tex:SetAlpha(.2);
				end
			end
		end
	end
end

local function MarkButtonsForReInit(self)
	for i,page in pairs(AP2_Header_Frame.Pages) do
		local children = {page:GetChildren()}
		for q,btn in ipairs(children) do
			btn.Initialized = nil
		end
	end
end

local function UpdateActionButtonState(self,elapsed)
	if self.Initialized == nil then
		self.Initialized = 1
		InitializeActionButton(self)
	end
	
	if not self:GetParent():IsVisible() then
		return
	end
	
	if self.showgrid == nil then
		button_CheckGrid(self)
		self.showgrid = nil
	end
	
	self.RANGE_CHECK_UPDATE = self.RANGE_CHECK_UPDATE + elapsed
	if self.RANGE_CHECK_UPDATE >= RANGE_CHECK_UPDATE then
		self.RANGE_CHECK_UPDATE = 0
		button_CheckRange(self)
	end
	
	
	self.TOOL_TIP_UPDATE = self.TOOL_TIP_UPDATE + elapsed
	if (self.TOOL_TIP_UPDATE >= TOOL_TIP_UPDATE) then
		self.TOOL_TIP_UPDATE = 0
		button_CheckToolTip(self)
	end
	
	self.REPEAT_UPDATE = self.REPEAT_UPDATE + elapsed
	if self.REPEAT_UPDATE >= REPEAT_UPDATE then
		self.REPEAT_UPDATE = 0
		
		button_RepeatUpdate(self)
	end
	
	
	self.COOLDOWN_UPDATE = self.COOLDOWN_UPDATE + elapsed
	if self.COOLDOWN_UPDATE >= COOLDOWN_UPDATE then
		self.COOLDOWN_UPDATE = 0
		button_CooldownUpdate(self)
	end	
	
end

local function buttonDragStart(btn)
	if (LOCK_ACTIONBAR ~= "1") then
		local mouseOver = GetMouseFocus();
		if (mouseOver:GetName() ~= nil and mouseOver:GetName() == btn:GetName()) then
			local actionID = SecureButton_GetModifiedAttribute(btn, "action");
			PickupAction(actionID);
			InitializeActionButton(btn);
			if (btn.floatFor ~= nil and btn.floatFor:IsVisible()) then
				buttonCheckLoadImage(btn.floatFor);
			end
		end
	end
end

local function buttonDragStop(btn)
	if (LOCK_ACTIONBAR ~= "1") then
		local mouseOver = GetMouseFocus();
		if (mouseOver:GetName() ~= nil and mouseOver:GetName() == btn:GetName()) then
			local actionID = SecureButton_GetModifiedAttribute(btn, "action");
			PlaceAction(actionID);
			InitializeActionButton(btn);
			if (btn.floatFor ~= nil and btn.floatFor:IsVisible()) then
				buttonCheckLoadImage(btn.floatFor);
			end
		end
	end
end

local function CreateActionButton(index,parent)
	local typ,id,subTyp = GetActionInfo(index)
	
	local actBtn = CreateFrame("CheckButton","AP2FormButton"..index,parent,"SecureActionButtonTemplate")
	actBtn:SetAttribute("type","action")
	actBtn:SetAttribute("action",index)
	actBtn:SetWidth(ABUTTON_SIZE)
	actBtn:SetHeight(ABUTTON_SIZE)
	
	local t = actBtn:CreateTexture(nil,"OVERLAY")
	t:SetBlendMode("ADD")
	t:SetAllPoints(actBtn)
	t:SetTexture(1,0,0,.5)
	t:Hide()
	actBtn.reptex = t
	
	t = actBtn:CreateTexture(nil,"OVERLAY")
	t:SetAllPoints(actBtn)
	t:SetTexture(0,0,0,.5)
	t:Hide()
	actBtn.cooldownbk = t
	
	t = actBtn:CreateFontString(nil,"OVERLAY","GameFontNormalHuge")
	t:SetAllPoints(actBtn)
	t:SetTextColor(1,1,0,1)
	t:Hide()
	actBtn.cooldown = t
	
	t = actBtn:CreateTexture(nil,"OVERLAY")
	t:SetBlendMode("ADD")
	t:SetTexture("Interface\\Buttons\\UI-ActionButton-Border")
	t:SetAllPoints(actBtn)
	t:Hide()
	t:SetTexCoord(.25,.75,.25,.75)
	actBtn.grid = t
	
	t = actBtn:CreateFontString(nil,"ARTWORK","NumberFontNormalSmallGray")
	t:SetJustifyH("RIGHT")
	t:SetWidth(36)
	t:SetHeight(10)
	t:SetPoint("TOPLEFT",actBtn,"TOPLEFT",-2,-2)
	actBtn.hotkey = t
	
	t = actBtn:CreateFontString(nil,"ARTWORK","NumberFontNormalSmall")
	t:SetJustifyH("RIGHT")
	t:SetWidth(36)
	t:SetHeight(10)
	t:SetPoint("BOTTOMRIGHT",actBtn,"BOTTOMRIGHT",0,2)
	actBtn.count = t
	
	actBtn.COOLDOWN_UPDATE = 0
	actBtn.REPEAT_UPDATE = 0
	actBtn.TOOL_TIP_UPDATE = 0
	actBtn.RANGE_CHECK_UPDATE = 0
	
	actBtn:SetScript("OnUpdate",UpdateActionButtonState)
	actBtn:RegisterForDrag("LeftButton", "RightButton");
	actBtn:SetScript("OnDragStart", buttonDragStart);
	actBtn:SetScript("OnReceiveDrag", buttonDragStop);
	
	return actBtn
end

local function CreateButtons()
	local buttonActionID = 1
	local PrevPage = nil
	for i = 1, NUM_PAGES do
		local Page = CreateFrame("Frame","AP2Page"..i,AP2_Header_Frame,"SecureFrameTemplate")
		AP2_Header_Frame.Pages[i] = Page
		
		AP2_Header_Frame:SetFrameRef("Page"..i,Page)
		
		Page:SetWidth(ABUTTON_SIZE*5)
		Page:SetHeight(ABUTTON_SIZE*4) -- purley a container for the buttons.. to do easy show hide
		Page:ClearAllPoints()
		Page:SetPoint("TOPLEFT",AP2_Header_Frame,"TOPLEFT",0,0)
		
		local btn = nil
		local prev = nil;
		
		local PageButtonCount = 1
		
		-- ############ ROW 1
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("TOPLEFT",Page,"TOPLEFT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		-- ############ ROW 2
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("TOPLEFT",Page,"TOPLEFT",0,-btn:GetHeight());
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		-- skip one for hte up arrow
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",btn:GetWidth(),0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		-- ############ ROW 3
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("TOPLEFT",Page,"TOPLEFT",0,-btn:GetHeight()*2);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		-- skip 3 for the arrows
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",btn:GetWidth()*3,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		-- ############ ROW 4
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("TOPLEFT",Page,"TOPLEFT",0,-btn:GetHeight()*3);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		btn = CreateActionButton(buttonActionID,Page);
		btn:SetPoint("LEFT",prev,"RIGHT",0,0);
		buttonActionID = buttonActionID + 1;
		AP2_Header_Frame:SetFrameRef("Page"..i.."Button"..PageButtonCount,btn);PageButtonCount=PageButtonCount+1
		prev = btn
		
		PrevPage = Page
	end
end

CreateHeaderFrame()
CreateExtraFrame()

local function SetupContainment()
	AP2_Header_Frame:SetAttribute("_onstate-stance", [[
		-- print("StanceUpdate; new state " .. tostring(newstate))
		control:RunAttribute("StanceUpdate",newstate)
	]])
	AP2_Header_Frame:SetAttribute("_onstate-page", [[
		control:RunAttribute("PageUpdate",newstate)
	]])
	AP2_Header_Frame:SetAttribute("_onstate-modifier", [[
		control:RunAttribute("ModifierUpdate",newstate)
	]])
	AP2_Header_Frame:SetAttribute("_onstate-stealth", [[
		control:RunAttribute("StealthUpdate",newstate)
	]])
	
	AP2_Header_Frame:SetAttribute("_onstate-pet", [[
		control:RunAttribute("PetUpdate",newstate)
	]])
	
--	AP2_Header_Frame:SetAttribute("_onattributechanged", [[
--		print(tostring(self) .. " (self) ")
--		print(tostring(name) .. " (name) ")
--		print(tostring(value) .. " (value) ")
--	]])
end

local function BuildExtraBar()
	local nButtons = 120 - NUM_BUTTONS * NUM_PAGES
	local buttonActionID = NUM_BUTTONS * NUM_PAGES + 1
	
	local last   = nil
	local colTop = nil
	local btn    = nil
	
	for i = 1, nButtons do
		if i == 1 then
			btn = CreateActionButton(buttonActionID,AP2_Extra_Frame);
			btn:SetPoint("TOPLEFT",AP2_Extra_Frame,"TOPLEFT",0,0);
			buttonActionID = buttonActionID + 1;
			last   = btn
			colTop = btn
		elseif mod(i-1,6) == 0 then
			btn = CreateActionButton(buttonActionID,AP2_Extra_Frame);
			if i == 13 then
				btn:SetPoint("TOPLEFT",colTop,"TOPRIGHT",colTop:GetWidth(),0);
			else
				btn:SetPoint("TOPLEFT",colTop,"TOPRIGHT",0,0);
			end
			buttonActionID = buttonActionID + 1;
			last   = btn
			colTop = btn
		else
			btn = CreateActionButton(buttonActionID,AP2_Extra_Frame);
			btn:SetPoint("TOP",last,"BOTTOM",0,0);
			buttonActionID = buttonActionID + 1;
			last   = btn
		end
	end
	
	if GetSavedVar(EXTRA_BAR_VIS,1) == 0 then
		AP2_Extra_Frame:Hide()
	else
		AP2_Extra_Frame:Show()
	end
end

local function HandleMainBar()
	if (GetSavedVar(MAIN_BAR_VIS,1) == 1) then
		if not MainMenuBar:IsVisible() and InCombatLockdown() == nil then
			ShowUIPanel(MainMenuBar)
		end
	else
		if MainMenuBar:IsVisible() and InCombatLockdown() == nil then
			HideUIPanel(MainMenuBar)
		end
	end
end

local function CreateUI()
	CreateButtons()
	AP2_Header_Frame:Execute("control:RunAttribute(\"ShowPage\",".. GetActionBarPage() .. ")")
	
	local stanceStr = "[stance:0] 0;"
	for i = 1, GetNumShapeshiftForms() do
		stanceStr = stanceStr .. "[stance:"..i.."] "..i..";-1	"
	end
	
	local pageStr = ""
	for i = 1, NUM_PAGES do
		pageStr = pageStr .. "[bar:" .. i .. "] "..i..";"
	end
	
	RegisterStateDriver(AP2_Header_Frame,"stance",stanceStr)
	RegisterStateDriver(AP2_Header_Frame,"page",pageStr)
	RegisterStateDriver(AP2_Header_Frame,"modifier","[modifier:shift] shift;[modifier:alt] alt;[modifier:ctrl] ctrl;off")
	RegisterStateDriver(AP2_Header_Frame,"stealth","[stealth] 1;0")
	RegisterStateDriver(AP2_Header_Frame,"pet","[pet] 1;0")
	BuildExtraBar()
	SetupContainment()
	LoadStatePages()
	HandleMainBar()
end

UpdateCurrentPageItemCounts = function ()
	local children = {AP2_Header_Frame.CurrentPage:GetChildren()}
	for i,btn in ipairs(children) do
		local actionID = SecureButton_GetModifiedAttribute(btn, "action");
		if (IsConsumableAction(actionID)) then
			btn.count:SetText(tostring(GetActionCount(actionID)));
		else
			btn.count:SetText("");
		end
	end
end


local function UpdateCurrentPageShowGrid()
	local children = {AP2_Header_Frame.CurrentPage:GetChildren()}
	for i,btn in ipairs(children) do
		btn.showgrid = 1
		button_CheckGrid(btn)
	end
end

local function UpdateCurrentPageHideGrid()
	for i,page in pairs(AP2_Header_Frame.Pages) do
		local children = {page:GetChildren()}
		for q,btn in ipairs(children) do
			btn.showgrid = 0
			button_CheckGrid(btn)
		end
	end
end

local function UpdateReInitAllButtons()
	local children = {AP2_Header_Frame.CurrentPage:GetChildren()}
	for i,btn in ipairs(children) do
		InitializeActionButton(btn)
	end
end

local function ExtraPageShowGrid()
	local children = {AP2_Extra_Frame:GetChildren()}
	for i,btn in ipairs(children) do
		btn.showgrid = 1
		button_CheckGrid(btn)
	end
end

local function ExtraPageHideGrid()
	local children = {AP2_Extra_Frame:GetChildren()}
	for i,btn in ipairs(children) do
		btn.showgrid = 0
		button_CheckGrid(btn)
	end
end

local function ExtraUpdatePageItemCounts()
	local children = {AP2_Extra_Frame:GetChildren()}
	for i,btn in ipairs(children) do
		local actionID = SecureButton_GetModifiedAttribute(btn, "action");
		if (IsConsumableAction(actionID)) then
			btn.count:SetText(tostring(GetActionCount(actionID)));
		else
			btn.count:SetText("");
		end
	end
end

local function ExtraReInitButtons()
	local children = {AP2_Extra_Frame:GetChildren()}
	for i,btn in ipairs(children) do
		btn.showgrid = 0
		--print("Re initing extra button actionID " .. btn:GetAttribute("action") .. " Has Action " .. tostring(HasAction(btn:GetAttribute("action"))))
		InitializeActionButton(btn)
	end
end


-- ################################### COMMAND handlers
local AP2_Toggle_Config = nil

local function AP2_SlashCmd(cmd)
	if string.lower(cmd) == "reset" then
		print("Resetting ActionPad2 Pad")
		AP2_Header_Frame:ClearAllPoints()
		AP2_Header_Frame:SetWidth(32)
		AP2_Header_Frame:SetHeight(32)
		AP2_Header_Frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
	else
		AP2_Toggle_Config()
	end
end

local function SetupCmd()
	SlashCmdList["AP2"] = AP2_SlashCmd;
	SLASH_AP21 = "/ap2" 
end

-- ################################### EVENT Frame
local eventFrame = CreateFrame("Frame","ActionPadEventFrame",UIParent,nil)
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("ACTIONBAR_SLOT_CHANGED")
eventFrame:RegisterEvent("UPDATE_BINDINGS")
eventFrame:RegisterEvent("ACTIONBAR_SHOWGRID")
eventFrame:RegisterEvent("ACTIONBAR_HIDEGRID")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:RegisterEvent("CHARACTER_POINTS_CHANGED");
eventFrame:RegisterEvent("PET_TALENT_POINTS_CHANGED");
eventFrame:RegisterEvent("PREVIEW_TALENT_POINTS_CHANGED");
eventFrame:RegisterEvent("PREVIEW_PET_TALENT_POINTS_CHANGED");
-- eventFrame:RegisterEvent("UNIT_ENTERED_VEHICLE")
-- eventFrame:RegisterEvent("UNIT_EXITED_VEHICLE") // fixed this by tracking the pet state

local lastActiveTalentSet = -1
local wasInVehicle = 0

eventFrame:SetScript("OnUpdate", function (self,elapsed,...)
									if LOADED == 1 then
										if lastActiveTalentSet == -1 then
											lastActiveTalentSet = GetActiveTalentGroup()
										elseif lastActiveTalentSet ~= GetActiveTalentGroup() then
											MarkButtonsForReInit()
											lastActiveTalentSet = GetActiveTalentGroup()
										end
										HandleMainBar()
									end
								end)

eventFrame:SetScript("OnEvent", function (self,event,...)
									if (event == "ADDON_LOADED" and select(1,...) == "SwitchF2") then
										local val = GetSavedVar(AP2_Header_Frame:GetName() .. "_scale",1)
										AP2_Header_Frame:SetScale(val);
										val = GetSavedVar(AP2_Extra_Frame:GetName() .. "_scale",1)
										AP2_Extra_Frame:SetScale(val)
									elseif (event == "PLAYER_LOGIN") then
										if LOADED == 0 then
											CreateUI()
											SetupCmd()
											LOADED = 1
										end
									elseif (event == "ACTIONBAR_SLOT_CHANGED") then
										if LOADED == 1 then
											UpdateCurrentPageItemCounts()
											UpdateReInitAllButtons()
											ExtraReInitButtons()
											ExtraUpdatePageItemCounts()
										end
									elseif (event == "UPDATE_BINDINGS") then
										if LOADED == 1 then
											UpdateAllHotKeyText()
											if InCombatLockdown() == nil then
												UpdateOverrideBindings()
											end
										end
									elseif (event == "ACTIONBAR_SHOWGRID") then
										if LOADED == 1 then
											UpdateCurrentPageShowGrid()
											ExtraPageShowGrid()
										end
									elseif (event == "ACTIONBAR_HIDEGRID") then
										if LOADED == 1 then
											UpdateCurrentPageHideGrid()
											ExtraPageHideGrid()
										end
									elseif (event == "PLAYER_ENTERING_WORLD") then
										HandleMainBar()
--									elseif (event == "UNIT_ENTERED_VEHICLE" or event == "UNIT_EXITED_VEHICLE") then
--										local inVeh = UnitHasVehicleUI('player')
										-- print("vech entered: " .. tostring(inVeh))
--										if wasInVehicle == 0 and inVeh then
--											wasInVehicle = 1
--											ClearOverrideBindings(AP2_Header_Frame)
--										elseif wasInVehicle == 1 and not inVeh then
--											wasInVehicle = 0
--											UpdateOverrideBindings()
--										end									
									end
								end)
								
								
-- ################################### CONFIG
local AP2_Config_Frame = nil
local AP2_Config_State = nil
local AP2_Config_FrameExtra = nil

local function pad_config_onUpdate(self,elapsed)
	local newScale = self.slider:GetValue()/100;
	if (apBar_LastScale == nil) then
		apBar_LastScale = self.control_parent:GetScale();
	end
	if (newScale ~= apBar_LastScale) then
		self.slider.text:SetText("Scale " .. newScale*100 ..  "%");
		
		local setL = floor(self.control_parent:GetLeft() * self.control_parent:GetScale() +0.5);
		local setT = floor(self.control_parent:GetTop() * self.control_parent:GetScale() + 0.5); -- note this is the distance from the top of the window to the bottom of the screen
		-- so to get the thing in TL respective coords UIParent:GetHeight()-setT should be the distance from the top
		setT = UIParent:GetHeight() - setT;
		
		self.control_parent:SetScale(newScale);
		self.control_parent:ClearAllPoints();
		self.control_parent:SetPoint("TOPLEFT",UIParent,"TOPLEFT", setL/self.control_parent:GetScale(),-setT/self.control_parent:GetScale());
		
		SetSavedVar(self.control_parent:GetName() .. "_scale",newScale);
		apBar_LastScale = newScale
	end
end

local function CreateConfigScale(name, control_parent)
	local cfg_pad = CreateFrame("Frame",name, UIParent, nil);
	cfg_pad.control_parent = control_parent;
	cfg_pad:SetWidth(250);
	cfg_pad:SetHeight(70);
	local bg = cfg_pad:CreateTexture(nil, "BACKGROUND");
	bg:SetTexture(0.5,0.5,0.5,0.5);
	bg:SetAllPoints(cfg_pad);
	
	cfg_pad:SetScript("OnUpdate",pad_config_onUpdate);
	cfg_pad:Hide();

	local lbl = cfg_pad:CreateFontString(nil, "TEXT");
	lbl:SetFontObject(GameFontNormalSmall);
	lbl:SetPoint("BOTTOMLEFT", cfg_pad, "TOPLEFT", 5, -10);
	lbl:SetText("Configuration");
	
	cfg_pad.slider = CreateFrame("Slider",name.."_scale", cfg_pad, "OptionsSliderTemplate");
	cfg_pad.slider:SetPoint("TOPLEFT",cfg_pad,"TOPLEFT",25,-20);
	cfg_pad.slider:SetWidth(cfg_pad:GetWidth() - 50);
	cfg_pad.slider:SetOrientation("HORIZONTAL");
	cfg_pad.slider:SetMinMaxValues(50,200);
	cfg_pad.slider:SetValue(control_parent:GetScale() * 100);
	cfg_pad.slider:SetValueStep(10);
	cfg_pad.slider.text = getglobal(cfg_pad.slider:GetName() .. "Text");
	cfg_pad.slider.text:SetText("Scale " .. cfg_pad.slider:GetValue() ..  "%");
	return cfg_pad;
end

local function state_config_onUpdate(self,elapsed)
end

local function StealthClick(self)
	-- print("Stealth clicked checked = " .. tostring(self:GetChecked()))
	if self:GetChecked() == 1 then
		AP2_Config_State.control_parent.StealthPage = AP2_Config_State.control_parent.CurrentPageIdx
		AP2_Config_State.control_parent:Execute("StealthPage = CurrentPageIdx")
	else
		AP2_Config_State.control_parent.StealthPage = -1
		AP2_Config_State.control_parent:Execute("StealthPage = -1")
	end
	SaveStealthPage()
	self:GetParent():UpdateChecks()
end

local function AltClick(self)
	if self:GetChecked() == 1 then
		AP2_Config_State.control_parent.ModPages["alt"] = AP2_Config_State.control_parent.CurrentPageIdx
		AP2_Config_State.control_parent:Execute("ModPages[\"alt\"] = CurrentPageIdx")
	else
		AP2_Config_State.control_parent.ModPages["alt"] = -1
		AP2_Config_State.control_parent:Execute("ModPages[\"alt\"] = -1")
	end
	SaveModPages()
	self:GetParent():UpdateChecks()
end

local function ShiftClick(self)
	if self:GetChecked() == 1 then
		AP2_Config_State.control_parent.ModPages["shift"] = AP2_Config_State.control_parent.CurrentPageIdx
		AP2_Config_State.control_parent:Execute("ModPages[\"shift\"] = CurrentPageIdx")
	else
		AP2_Config_State.control_parent.ModPages["shift"] = -1
		AP2_Config_State.control_parent:Execute("ModPages[\"shift\"] = -1")
	end
	SaveModPages()
	self:GetParent():UpdateChecks()
end

local function CtrlClick(self)
	if self:GetChecked() == 1 then
		AP2_Config_State.control_parent.ModPages["ctrl"] = AP2_Config_State.control_parent.CurrentPageIdx
		AP2_Config_State.control_parent:Execute("ModPages[\"ctrl\"] = CurrentPageIdx")
	else
		AP2_Config_State.control_parent.ModPages["ctrl"] = -1
		AP2_Config_State.control_parent:Execute("ModPages[\"ctrl\"] = -1")
	end
	SaveModPages()
	self:GetParent():UpdateChecks()
end

local function FormClick(self)
	if self:GetChecked() == 1 then
		AP2_Config_State.control_parent.StancePages[self:GetID()] = AP2_Config_State.control_parent.CurrentPageIdx
		AP2_Config_State.control_parent:Execute("StancePages[" .. self:GetID() .. "] = CurrentPageIdx")
	else
		AP2_Config_State.control_parent.ModPages[self:GetID()] = -1
		AP2_Config_State.control_parent:Execute("StancePages[" .. self:GetID() .. "] = -1")
	end
	SaveStancePages()
	self:GetParent():UpdateChecks()
end

local function CreateStateConfig(name, control_parent)
	local pad = CreateFrame("Frame",name,UIParent,nil)
	pad:SetWidth(250)
	pad:SetHeight(29*(2+GetNumShapeshiftForms()))
	pad:SetScript("OnUpdate",state_config_onUpdate);
	local bg = pad:CreateTexture(nil, "BACKGROUND");
	bg:SetTexture(0.5,0.5,0.5,0.5);
	bg:SetAllPoints(pad);
	
	pad.control_parent = control_parent
	pad.UpdateChecks = function(self)
							if self.control_parent.StealthPage ~= nil then
								if self.control_parent.StealthPage == self.control_parent.CurrentPageIdx then
									self.StealthCheck:SetChecked(1)
								else
									self.StealthCheck:SetChecked(0)
								end
							end
							
							if self.control_parent.ModPages ~= nil then
								if self.control_parent.ModPages["ctrl"] == self.control_parent.CurrentPageIdx then
									self.CtlCheck:SetChecked(1)
								else
									self.CtlCheck:SetChecked(0)
								end
								if self.control_parent.ModPages["shift"] == self.control_parent.CurrentPageIdx then
									self.ShiftCheck:SetChecked(1)
								else
									self.ShiftCheck:SetChecked(0)
								end
								if self.control_parent.ModPages["alt"] == self.control_parent.CurrentPageIdx then
									self.AltCheck:SetChecked(1)
								else
									self.AltCheck:SetChecked(0)
								end
							end
							
							if self.control_parent.StancePages ~= nil then
								for i = 1,GetNumShapeshiftForms() do
									if self.control_parent.StancePages[i] == self.control_parent.CurrentPageIdx then
										self.FormCheck[i]:SetChecked(1)
									else
										self.FormCheck[i]:SetChecked(0)
									end
								end
							end
							
						end
	
	-- ####### STEALTH
	local lbl = pad:CreateFontString(nil, "TEXT");
	lbl:SetFontObject(GameFontNormalSmall);
	lbl:SetPoint("TOPLEFT", pad, "TOPLEFT", 5, -3);
	lbl:SetText("Stealth");
	
	local btn = CreateFrame("CheckButton","StealthBtn",pad,"UICheckButtonTemplate")
	btn:SetWidth(20)
	btn:SetHeight(20)
	btn:SetPoint("LEFT", lbl, "RIGHT", 10, 0)
	btn:SetScript("OnClick",StealthClick)
	pad.StealthCheck = btn
	
	
	-- ####### MODIFIERS
	lbl = pad:CreateFontString(nil, "TEXT")
	lbl:SetFontObject(GameFontNormalSmall)
	lbl:SetPoint("TOPLEFT", pad, "TOPLEFT", 5, -29)
	lbl:SetText("Shift:")
	local prev = lbl
	local shift = lbl
	
	btn = CreateFrame("CheckButton","ShiftBtn",pad,"UICheckButtonTemplate")
	btn:SetWidth(20)
	btn:SetHeight(20)
	btn:SetPoint("LEFT", lbl, "RIGHT", 10, 0);
	btn:SetScript("OnClick",ShiftClick)
	pad.ShiftCheck = btn

	
	lbl = pad:CreateFontString(nil, "TEXT");
	lbl:SetFontObject(GameFontNormalSmall);
	lbl:SetPoint("TOPLEFT", prev, "TOPRIGHT", 30, 0);
	lbl:SetText("Ctl:");
	prev = lbl
	btn = CreateFrame("CheckButton","CtlBtn",pad,"UICheckButtonTemplate")
	btn:SetWidth(20)
	btn:SetHeight(20)
	btn:SetPoint("LEFT", lbl, "RIGHT", 10, 0);
	btn:SetScript("OnClick",CtrlClick)
	pad.CtlCheck = btn
	
	lbl = pad:CreateFontString(nil, "TEXT");
	lbl:SetFontObject(GameFontNormalSmall);
	lbl:SetPoint("TOPLEFT", prev, "TOPRIGHT", 30, 0);
	lbl:SetText("Alt:");
	btn = CreateFrame("CheckButton","AltBtn",pad,"UICheckButtonTemplate")
	btn:SetWidth(20)
	btn:SetHeight(20)
	btn:SetPoint("LEFT", lbl, "RIGHT", 10, 0)
	btn:SetScript("OnClick",AltClick)
	pad.AltCheck = btn
	
	prev = shift
	
	pad.FormCheck = {}
	-- ####### STANCE
	for i = 1,GetNumShapeshiftForms() do
		local icon,name,active = GetShapeshiftFormInfo(i)
		
		lbl = pad:CreateFontString(nil, "TEXT");
		lbl:SetFontObject(GameFontNormalSmall);
		lbl:SetText(name);
		
		btn = CreateFrame("CheckButton",name.."Btn",pad,"UICheckButtonTemplate")
		btn:SetID(i)
		btn:SetWidth(20)
		btn:SetHeight(20)
		btn:SetPoint("LEFT", lbl, "RIGHT", 10, 0);
		btn:SetScript("OnClick",FormClick)
		pad.FormCheck[i] = btn

		lbl:SetPoint("TOPLEFT", prev, "BOTTOMLEFT", 0, -20)
		prev = lbl
	end
	
	pad.UpdateChecks(pad)
	
	return pad
end

Config_UpdatePage = function(page)
	if AP2_Config_State ~= nil and AP2_Config_State:IsVisible() then
		AP2_Config_State.UpdateChecks(AP2_Config_State)
	end
end


AP2_Toggle_Config = function()
	if not AP2_Config_Frame then
		AP2_Config_Frame = CreateConfigScale("AP2_Scale_Frame",AP2_Header_Frame)
	end
	
	if not AP2_Config_State then
		AP2_Config_State = CreateStateConfig("AP2_State_Config",AP2_Header_Frame)
	end
	
	if not AP2_Config_FrameExtra then
		AP2_Config_FrameExtra = CreateConfigScale("AP2_State_Config",AP2_Extra_Frame)
	end
	
	if AP2_Config_Frame:IsVisible() then
		AP2_Config_Frame:Hide()
		AP2_Config_State:Hide()
		AP2_Config_FrameExtra:Hide()
		AP2_Header_Frame:RegisterForDrag("LeftButton")
		if AP2_Extra_Frame:IsVisible() then
			AP2_Config_FrameExtra:RegisterForDrag("LeftButton")
		end
	else
		AP2_Header_Frame:RegisterForDrag(nil)
		if AP2_Extra_Frame:IsVisible() then
			AP2_Config_FrameExtra:RegisterForDrag(nil)
		end
		
		local pX = AP2_Config_Frame.control_parent:GetLeft() * AP2_Config_Frame.control_parent:GetScale()
		local pY = AP2_Config_Frame.control_parent:GetScale() * AP2_Config_Frame.control_parent:GetTop()
		AP2_Config_Frame:SetPoint("TOPLEFT",UIParent,"TOPLEFT", pX, -(AP2_Config_Frame:GetParent():GetTop() - pY)  + AP2_Config_Frame:GetHeight())
		AP2_Config_Frame:Show()
		
		AP2_Config_State:SetPoint("TOPLEFT",AP2_Header_Frame,"BOTTOMLEFT",0,0)
		AP2_Config_State:Show()
		
		if AP2_Extra_Frame:IsVisible() then
			local pX = AP2_Config_FrameExtra.control_parent:GetLeft() * AP2_Config_FrameExtra.control_parent:GetScale()
			local pY = AP2_Config_FrameExtra.control_parent:GetScale() * AP2_Config_FrameExtra.control_parent:GetTop()
			AP2_Config_FrameExtra:SetPoint("TOPLEFT",UIParent,"TOPLEFT", pX, -(AP2_Config_FrameExtra:GetParent():GetTop() - pY)  + AP2_Config_FrameExtra:GetHeight())
			AP2_Config_FrameExtra:Show()
		end
	end
end

--#####################################  Globals
function AP2_Toggle_Configure()
	AP2_Toggle_Config()
end

function AP2_Toggle_Mainbar()
	if (MainMenuBar:IsVisible()) then
		SetSavedVar(MAIN_BAR_VIS,0);
		HideUIPanel(MainMenuBar);
	else
		SetSavedVar(MAIN_BAR_VIS,1);
		ShowUIPanel(MainMenuBar);
	end
end

function AP2_Toggle_Extrabar()
	if (AP2_Extra_Frame:IsVisible()) then
		SetSavedVar(EXTRA_BAR_VIS,0);
		AP2_Extra_Frame:Hide();
	else
		SetSavedVar(EXTRA_BAR_VIS,1);
		AP2_Extra_Frame:Show();
	end
end
